<script setup>
import {getCurrentInstance, onMounted, reactive, ref, watch } from "vue";
import { useRouter } from 'vue-router';
import {permissionRouterRelationPage,roleRouterRelationPage,routerBindingInvoke, selectRouterById} from "@/api/basal.js";
import {ResultEnums} from "@/enums/ResultStatusEnums.js";
import Pagination from "@/components/debris/Pagination.vue";
const router = useRouter();
const {proxy} = getCurrentInstance();
const form = reactive({createSystemCode: proxy.$route.query.systemCode,isEnable:true, id:proxy.$route.query.id,sort:0,
  routerDescribed:'',routerUrl:'',requestType:'',routerSignboard:''});
const queryParams = reactive({pageNo:1,pageSize:10,createSystemCode: proxy.$route.query.systemCode,keyword:''})
const bindingStatus = ref("1")
const keyword = ref("")
const total = ref(0)
const rows = ref([])
const relation = ref(null)
const relationName = ref(null)
onMounted(() => {
  onLoadInfo( proxy.$route.query.systemCode, proxy.$route.query.id)
  var tabs = relation.value.querySelectorAll('a[data-bs-toggle="tab"]');
  for(const tab of tabs){
    if(tab.classList.contains('active')){
      relationName.value = tab.getAttribute('aria-controls')
    }
    tab.addEventListener('shown.bs.tab', function (event) {
      relationName.value = tab.getAttribute('aria-controls')
    })
  }
})

watch(bindingStatus,() => {
  onLoadRelationInfo(relationName.value,bindingStatus.value,proxy.$route.query.id,queryParams)
})

watch(queryParams,(newParams) => {
  onLoadRelationInfo(relationName.value,bindingStatus.value,proxy.$route.query.id,newParams)
})

watch(relationName,(newParams) => {
  keyword.value = ''
  bindingStatus.value = '1'
  onLoadRelationInfo(newParams,bindingStatus.value,proxy.$route.query.id,queryParams)
})

async function onLoadInfo(systemCode,id){
  let result = await selectRouterById(systemCode,id);
  if(result.code === ResultEnums.SUCCESS ){
    const data = result.data
    for(const key in data){
      form[key] = data[key]
    }
  }
}

async function onLoadRelationInfo(relation,bindingStatus,roleId,params){
  switch (relation) {
    case 'router-role':
      const loginResult = await roleRouterRelationPage(bindingStatus,roleId,params);
      if(loginResult.code === ResultEnums.SUCCESS ){
        const data = loginResult.data
        total.value = data.total
        rows.value = data.records
      }
      break;
    case 'router-permission':
      const permissionResult = await permissionRouterRelationPage(bindingStatus,roleId,params);
      if(permissionResult.code === ResultEnums.SUCCESS ){
        const data = permissionResult.data
        total.value = data.total
        rows.value = data.records
      }
      break
  }
}

async function bindingFunction(e,relation,bindingStatus,relationId){
  e.preventDefault();
  const routerId = proxy.$route.query.id
  switch (relation) {
    case 'router-role':
      await routerBindingInvoke(bindingStatus,routerId,relationId,'1')
      await  onLoadRelationInfo(relation,bindingStatus==='1'?'0':'1',routerId,queryParams)
      break;
    case 'router-permission':
      await routerBindingInvoke(bindingStatus,routerId,relationId,'0')
      await onLoadRelationInfo(relation,bindingStatus==='1'?'0':'1',routerId,queryParams)
      break;
    default:
      await onLoadRelationInfo(relation,bindingStatus==='1'?'0':'1',routerId,queryParams)
  }
}

function searchClick(e){
  e.preventDefault();
  queryParams.keyword = keyword.value;
}
</script>

<template>
  <h1 class="app-page-title" v-if="proxy.$route.meta">
    <a href="#" @click="(e)=>{e.preventDefault();router.go(-1);}"> <i class="bi bi-reply-all"></i></a> {{ proxy.$route.meta.theme }}
  </h1>
  <hr class="mb-4">
  <div class="row g-4 settings-section">
    <div class="col-12 col-md-4">
      <div class="section-intro">
        <div class="app-card-account d-flex flex-column align-items-start">
          <div class="app-card-body px-4 w-100">
            <div class="item border-bottom py-3">
              <div class="row justify-content-between align-items-center">
                <div class="item-label"><strong>描述</strong></div>
                <div class="item-data">{{ form.routerDescribed }}</div>
              </div><!--//row-->
            </div><!--//item-->
            <div class="item border-bottom py-3">
              <div class="row justify-content-between align-items-center">
                <div class="item-label"><strong>扫描地址</strong></div>
                <div class="item-data">{{ form.routerUrl }}</div>
              </div><!--//row-->
            </div><!--//item-->
            <div class="item border-bottom py-3">
              <div class="row justify-content-between align-items-center">
                <div class="item-label"><strong>请求类型</strong></div>
                <div class="item-data">
                  {{ {GET:'查询请求',POST:'提交请求',PUT:'修改请求',DELETE:'删除请求'}[form.requestType]||'未知请求'}}
                </div>
              </div><!--//row-->
            </div><!--//item-->
            <div class="item border-bottom py-3">
              <div class="row justify-content-between align-items-center">
                <div class="item-label"><strong>分组信息</strong></div>
                <div class="item-data">{{ form.routerSignboard }}</div>
              </div><!--//row-->
            </div><!--//item-->
          </div><!--//app-card-body-->
        </div><!--//app-card-->
      </div>
    </div>
    <div class="col-12 col-md-8">
      <div class="row g-3 mb-4 align-items-center justify-content-between">
        <div class="col-auto">
          <div class="page-utilities">
            <div class="row g-2 justify-content-start justify-content-md-end align-items-center">
              <div class="col-auto">
                <form class="table-search-form row gx-1 align-items-center">
                  <div class="col-auto">
                    <input type="text" id="search-orders" v-model="keyword" class="form-control search-orders" placeholder="关键字">
                  </div>
                  <div class="col-auto">
                    <button type="submit" class="btn app-btn-secondary" @click="searchClick">查询</button>
                  </div>
                </form>
              </div><!--//col-->
              <div class="col-auto">
                <select class="form-select w-auto" v-model="bindingStatus">
                  <option value="1">已绑定</option>
                  <option value="0">未绑定</option>
                </select>
              </div>
            </div>
          </div>
        </div>
      </div>
      <nav id="relation-router-tab" ref="relation" class="relation-router-tab app-nav-tabs nav shadow-sm flex-column flex-sm-row mb-4">
        <a class="flex-sm-fill text-sm-center nav-link active" id="router-role-tab" data-bs-toggle="tab" href="#router-role" role="tab"
           aria-controls="router-role" aria-selected="true">路由角色关系绑定</a>
        <a class="flex-sm-fill text-sm-center nav-link" id="router-permission-tab" data-bs-toggle="tab" href="#router-permission" role="tab"
           aria-controls="router-permission" aria-selected="true">路由权限关系绑定</a>
      </nav>
      <div class="tab-content" id="relation-router-tab-content">
        <div class="tab-pane fade show active" id="router-role" role="tabpanel" aria-labelledby="router-role-tab">
          <div class="app-card app-card-orders-table shadow-sm mb-5">
            <div class="app-card-body">
              <div class="table-responsive">
                <table class="table app-table-hover mb-0 text-left">
                  <thead>
                  <tr>
                    <th class="cell">角色名称</th>
                    <th class="cell">角色编码</th>
                    <th class="cell"></th>
                  </tr>
                  </thead>
                  <tbody v-if="rows">
                  <tr v-for="row in rows">
                    <td class="cell">{{ row.roleName }}</td>
                    <td class="cell">{{ row.roleCode }}</td>
                    <!-- menuBindingFunction   -->
                    <td class="cell">
                      <template v-if="bindingStatus === '1'">
                        <button type="button" class="btn btn-outline-info btn-sm" @click="bindingFunction($event,relationName,'0',row.id)" >解绑</button>
                      </template>
                      <template v-else>
                        <button type="button" class="btn btn-outline-primary btn-sm" @click="bindingFunction($event,relationName,'1',row.id)" >绑定</button>
                      </template>
                    </td>
                  </tr>
                  </tbody>
                </table>
              </div><!--//table-responsive-->
            </div><!--//app-card-body-->
          </div><!--//app-card-->
          <Pagination :page-size=queryParams.pageSize :total=total :span=2 @current-change="(num)=>{queryParams.pageNo=num}"/><!--//app-pagination-->
        </div>
        <div class="tab-pane fade show" id="router-permission" role="tabpanel" aria-labelledby="router-permission-tab">
          <div class="app-card app-card-orders-table shadow-sm mb-5">
            <div class="app-card-body">
              <div class="table-responsive">
                <table class="table app-table-hover mb-0 text-left">
                  <thead>
                  <tr>
                    <th class="cell">权限名称</th>
                    <th class="cell">权限编码</th>
                    <th class="cell">权限分组</th>
                    <th class="cell">操作</th>
                  </tr>
                  </thead>
                  <tbody v-if="rows">
                  <tr v-for="row in rows">
                    <td class="cell">{{ row.permissionName }}</td>
                    <td class="cell">{{ row.permissionCode }}</td>
                    <td class="cell">{{ row.permissionSignboard }}</td>
                    <!-- menuBindingFunction   -->
                    <td class="cell">
                      <template v-if="bindingStatus === '1'">
                        <button type="button" class="btn btn-outline-info btn-sm" @click="bindingFunction($event,relationName,'0',row.id)" >解绑</button>
                      </template>
                      <template v-else>
                        <button type="button" class="btn btn-outline-primary btn-sm" @click="bindingFunction($event,relationName,'1',row.id)" >绑定</button>
                      </template>
                    </td>
                  </tr>
                  </tbody>
                </table>
              </div><!--//table-responsive-->
            </div><!--//app-card-body-->
          </div><!--//app-card-->
          <Pagination :page-size=queryParams.pageSize :total=total :span=2 @current-change="(num)=>{queryParams.pageNo=num}"/><!--//app-pagination-->
        </div>
      </div>
    </div>
  </div>
</template>